wheel.py 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018
  1. # -*- coding: utf-8 -*-
  2. #
  3. # Copyright (C) 2013-2017 Vinay Sajip.
  4. # Licensed to the Python Software Foundation under a contributor agreement.
  5. # See LICENSE.txt and CONTRIBUTORS.txt.
  6. #
  7. from __future__ import unicode_literals
  8. import base64
  9. import codecs
  10. import datetime
  11. import distutils.util
  12. from email import message_from_file
  13. import hashlib
  14. import imp
  15. import json
  16. import logging
  17. import os
  18. import posixpath
  19. import re
  20. import shutil
  21. import sys
  22. import tempfile
  23. import zipfile
  24. from . import __version__, DistlibException
  25. from .compat import sysconfig, ZipFile, fsdecode, text_type, filter
  26. from .database import InstalledDistribution
  27. from .metadata import (Metadata, METADATA_FILENAME, WHEEL_METADATA_FILENAME,
  28. LEGACY_METADATA_FILENAME)
  29. from .util import (FileOperator, convert_path, CSVReader, CSVWriter, Cache,
  30. cached_property, get_cache_base, read_exports, tempdir)
  31. from .version import NormalizedVersion, UnsupportedVersionError
  32. logger = logging.getLogger(__name__)
  33. cache = None # created when needed
  34. if hasattr(sys, 'pypy_version_info'): # pragma: no cover
  35. IMP_PREFIX = 'pp'
  36. elif sys.platform.startswith('java'): # pragma: no cover
  37. IMP_PREFIX = 'jy'
  38. elif sys.platform == 'cli': # pragma: no cover
  39. IMP_PREFIX = 'ip'
  40. else:
  41. IMP_PREFIX = 'cp'
  42. VER_SUFFIX = sysconfig.get_config_var('py_version_nodot')
  43. if not VER_SUFFIX: # pragma: no cover
  44. VER_SUFFIX = '%s%s' % sys.version_info[:2]
  45. PYVER = 'py' + VER_SUFFIX
  46. IMPVER = IMP_PREFIX + VER_SUFFIX
  47. ARCH = distutils.util.get_platform().replace('-', '_').replace('.', '_')
  48. ABI = sysconfig.get_config_var('SOABI')
  49. if ABI and ABI.startswith('cpython-'):
  50. ABI = ABI.replace('cpython-', 'cp')
  51. else:
  52. def _derive_abi():
  53. parts = ['cp', VER_SUFFIX]
  54. if sysconfig.get_config_var('Py_DEBUG'):
  55. parts.append('d')
  56. if sysconfig.get_config_var('WITH_PYMALLOC'):
  57. parts.append('m')
  58. if sysconfig.get_config_var('Py_UNICODE_SIZE') == 4:
  59. parts.append('u')
  60. return ''.join(parts)
  61. ABI = _derive_abi()
  62. del _derive_abi
  63. FILENAME_RE = re.compile(r'''
  64. (?P<nm>[^-]+)
  65. -(?P<vn>\d+[^-]*)
  66. (-(?P<bn>\d+[^-]*))?
  67. -(?P<py>\w+\d+(\.\w+\d+)*)
  68. -(?P<bi>\w+)
  69. -(?P<ar>\w+(\.\w+)*)
  70. \.whl$
  71. ''', re.IGNORECASE | re.VERBOSE)
  72. NAME_VERSION_RE = re.compile(r'''
  73. (?P<nm>[^-]+)
  74. -(?P<vn>\d+[^-]*)
  75. (-(?P<bn>\d+[^-]*))?$
  76. ''', re.IGNORECASE | re.VERBOSE)
  77. SHEBANG_RE = re.compile(br'\s*#![^\r\n]*')
  78. SHEBANG_DETAIL_RE = re.compile(br'^(\s*#!("[^"]+"|\S+))\s+(.*)$')
  79. SHEBANG_PYTHON = b'#!python'
  80. SHEBANG_PYTHONW = b'#!pythonw'
  81. if os.sep == '/':
  82. to_posix = lambda o: o
  83. else:
  84. to_posix = lambda o: o.replace(os.sep, '/')
  85. class Mounter(object):
  86. def __init__(self):
  87. self.impure_wheels = {}
  88. self.libs = {}
  89. def add(self, pathname, extensions):
  90. self.impure_wheels[pathname] = extensions
  91. self.libs.update(extensions)
  92. def remove(self, pathname):
  93. extensions = self.impure_wheels.pop(pathname)
  94. for k, v in extensions:
  95. if k in self.libs:
  96. del self.libs[k]
  97. def find_module(self, fullname, path=None):
  98. if fullname in self.libs:
  99. result = self
  100. else:
  101. result = None
  102. return result
  103. def load_module(self, fullname):
  104. if fullname in sys.modules:
  105. result = sys.modules[fullname]
  106. else:
  107. if fullname not in self.libs:
  108. raise ImportError('unable to find extension for %s' % fullname)
  109. result = imp.load_dynamic(fullname, self.libs[fullname])
  110. result.__loader__ = self
  111. parts = fullname.rsplit('.', 1)
  112. if len(parts) > 1:
  113. result.__package__ = parts[0]
  114. return result
  115. _hook = Mounter()
  116. class Wheel(object):
  117. """
  118. Class to build and install from Wheel files (PEP 427).
  119. """
  120. wheel_version = (1, 1)
  121. hash_kind = 'sha256'
  122. def __init__(self, filename=None, sign=False, verify=False):
  123. """
  124. Initialise an instance using a (valid) filename.
  125. """
  126. self.sign = sign
  127. self.should_verify = verify
  128. self.buildver = ''
  129. self.pyver = [PYVER]
  130. self.abi = ['none']
  131. self.arch = ['any']
  132. self.dirname = os.getcwd()
  133. if filename is None:
  134. self.name = 'dummy'
  135. self.version = '0.1'
  136. self._filename = self.filename
  137. else:
  138. m = NAME_VERSION_RE.match(filename)
  139. if m:
  140. info = m.groupdict('')
  141. self.name = info['nm']
  142. # Reinstate the local version separator
  143. self.version = info['vn'].replace('_', '-')
  144. self.buildver = info['bn']
  145. self._filename = self.filename
  146. else:
  147. dirname, filename = os.path.split(filename)
  148. m = FILENAME_RE.match(filename)
  149. if not m:
  150. raise DistlibException('Invalid name or '
  151. 'filename: %r' % filename)
  152. if dirname:
  153. self.dirname = os.path.abspath(dirname)
  154. self._filename = filename
  155. info = m.groupdict('')
  156. self.name = info['nm']
  157. self.version = info['vn']
  158. self.buildver = info['bn']
  159. self.pyver = info['py'].split('.')
  160. self.abi = info['bi'].split('.')
  161. self.arch = info['ar'].split('.')
  162. @property
  163. def filename(self):
  164. """
  165. Build and return a filename from the various components.
  166. """
  167. if self.buildver:
  168. buildver = '-' + self.buildver
  169. else:
  170. buildver = ''
  171. pyver = '.'.join(self.pyver)
  172. abi = '.'.join(self.abi)
  173. arch = '.'.join(self.arch)
  174. # replace - with _ as a local version separator
  175. version = self.version.replace('-', '_')
  176. return '%s-%s%s-%s-%s-%s.whl' % (self.name, version, buildver,
  177. pyver, abi, arch)
  178. @property
  179. def exists(self):
  180. path = os.path.join(self.dirname, self.filename)
  181. return os.path.isfile(path)
  182. @property
  183. def tags(self):
  184. for pyver in self.pyver:
  185. for abi in self.abi:
  186. for arch in self.arch:
  187. yield pyver, abi, arch
  188. @cached_property
  189. def metadata(self):
  190. pathname = os.path.join(self.dirname, self.filename)
  191. name_ver = '%s-%s' % (self.name, self.version)
  192. info_dir = '%s.dist-info' % name_ver
  193. wrapper = codecs.getreader('utf-8')
  194. with ZipFile(pathname, 'r') as zf:
  195. wheel_metadata = self.get_wheel_metadata(zf)
  196. wv = wheel_metadata['Wheel-Version'].split('.', 1)
  197. file_version = tuple([int(i) for i in wv])
  198. # if file_version < (1, 1):
  199. # fns = [WHEEL_METADATA_FILENAME, METADATA_FILENAME,
  200. # LEGACY_METADATA_FILENAME]
  201. # else:
  202. # fns = [WHEEL_METADATA_FILENAME, METADATA_FILENAME]
  203. fns = [WHEEL_METADATA_FILENAME, LEGACY_METADATA_FILENAME]
  204. result = None
  205. for fn in fns:
  206. try:
  207. metadata_filename = posixpath.join(info_dir, fn)
  208. with zf.open(metadata_filename) as bf:
  209. wf = wrapper(bf)
  210. result = Metadata(fileobj=wf)
  211. if result:
  212. break
  213. except KeyError:
  214. pass
  215. if not result:
  216. raise ValueError('Invalid wheel, because metadata is '
  217. 'missing: looked in %s' % ', '.join(fns))
  218. return result
  219. def get_wheel_metadata(self, zf):
  220. name_ver = '%s-%s' % (self.name, self.version)
  221. info_dir = '%s.dist-info' % name_ver
  222. metadata_filename = posixpath.join(info_dir, 'WHEEL')
  223. with zf.open(metadata_filename) as bf:
  224. wf = codecs.getreader('utf-8')(bf)
  225. message = message_from_file(wf)
  226. return dict(message)
  227. @cached_property
  228. def info(self):
  229. pathname = os.path.join(self.dirname, self.filename)
  230. with ZipFile(pathname, 'r') as zf:
  231. result = self.get_wheel_metadata(zf)
  232. return result
  233. def process_shebang(self, data):
  234. m = SHEBANG_RE.match(data)
  235. if m:
  236. end = m.end()
  237. shebang, data_after_shebang = data[:end], data[end:]
  238. # Preserve any arguments after the interpreter
  239. if b'pythonw' in shebang.lower():
  240. shebang_python = SHEBANG_PYTHONW
  241. else:
  242. shebang_python = SHEBANG_PYTHON
  243. m = SHEBANG_DETAIL_RE.match(shebang)
  244. if m:
  245. args = b' ' + m.groups()[-1]
  246. else:
  247. args = b''
  248. shebang = shebang_python + args
  249. data = shebang + data_after_shebang
  250. else:
  251. cr = data.find(b'\r')
  252. lf = data.find(b'\n')
  253. if cr < 0 or cr > lf:
  254. term = b'\n'
  255. else:
  256. if data[cr:cr + 2] == b'\r\n':
  257. term = b'\r\n'
  258. else:
  259. term = b'\r'
  260. data = SHEBANG_PYTHON + term + data
  261. return data
  262. def get_hash(self, data, hash_kind=None):
  263. if hash_kind is None:
  264. hash_kind = self.hash_kind
  265. try:
  266. hasher = getattr(hashlib, hash_kind)
  267. except AttributeError:
  268. raise DistlibException('Unsupported hash algorithm: %r' % hash_kind)
  269. result = hasher(data).digest()
  270. result = base64.urlsafe_b64encode(result).rstrip(b'=').decode('ascii')
  271. return hash_kind, result
  272. def write_record(self, records, record_path, base):
  273. records = list(records) # make a copy, as mutated
  274. p = to_posix(os.path.relpath(record_path, base))
  275. records.append((p, '', ''))
  276. with CSVWriter(record_path) as writer:
  277. for row in records:
  278. writer.writerow(row)
  279. def write_records(self, info, libdir, archive_paths):
  280. records = []
  281. distinfo, info_dir = info
  282. hasher = getattr(hashlib, self.hash_kind)
  283. for ap, p in archive_paths:
  284. with open(p, 'rb') as f:
  285. data = f.read()
  286. digest = '%s=%s' % self.get_hash(data)
  287. size = os.path.getsize(p)
  288. records.append((ap, digest, size))
  289. p = os.path.join(distinfo, 'RECORD')
  290. self.write_record(records, p, libdir)
  291. ap = to_posix(os.path.join(info_dir, 'RECORD'))
  292. archive_paths.append((ap, p))
  293. def build_zip(self, pathname, archive_paths):
  294. with ZipFile(pathname, 'w', zipfile.ZIP_DEFLATED) as zf:
  295. for ap, p in archive_paths:
  296. logger.debug('Wrote %s to %s in wheel', p, ap)
  297. zf.write(p, ap)
  298. def build(self, paths, tags=None, wheel_version=None):
  299. """
  300. Build a wheel from files in specified paths, and use any specified tags
  301. when determining the name of the wheel.
  302. """
  303. if tags is None:
  304. tags = {}
  305. libkey = list(filter(lambda o: o in paths, ('purelib', 'platlib')))[0]
  306. if libkey == 'platlib':
  307. is_pure = 'false'
  308. default_pyver = [IMPVER]
  309. default_abi = [ABI]
  310. default_arch = [ARCH]
  311. else:
  312. is_pure = 'true'
  313. default_pyver = [PYVER]
  314. default_abi = ['none']
  315. default_arch = ['any']
  316. self.pyver = tags.get('pyver', default_pyver)
  317. self.abi = tags.get('abi', default_abi)
  318. self.arch = tags.get('arch', default_arch)
  319. libdir = paths[libkey]
  320. name_ver = '%s-%s' % (self.name, self.version)
  321. data_dir = '%s.data' % name_ver
  322. info_dir = '%s.dist-info' % name_ver
  323. archive_paths = []
  324. # First, stuff which is not in site-packages
  325. for key in ('data', 'headers', 'scripts'):
  326. if key not in paths:
  327. continue
  328. path = paths[key]
  329. if os.path.isdir(path):
  330. for root, dirs, files in os.walk(path):
  331. for fn in files:
  332. p = fsdecode(os.path.join(root, fn))
  333. rp = os.path.relpath(p, path)
  334. ap = to_posix(os.path.join(data_dir, key, rp))
  335. archive_paths.append((ap, p))
  336. if key == 'scripts' and not p.endswith('.exe'):
  337. with open(p, 'rb') as f:
  338. data = f.read()
  339. data = self.process_shebang(data)
  340. with open(p, 'wb') as f:
  341. f.write(data)
  342. # Now, stuff which is in site-packages, other than the
  343. # distinfo stuff.
  344. path = libdir
  345. distinfo = None
  346. for root, dirs, files in os.walk(path):
  347. if root == path:
  348. # At the top level only, save distinfo for later
  349. # and skip it for now
  350. for i, dn in enumerate(dirs):
  351. dn = fsdecode(dn)
  352. if dn.endswith('.dist-info'):
  353. distinfo = os.path.join(root, dn)
  354. del dirs[i]
  355. break
  356. assert distinfo, '.dist-info directory expected, not found'
  357. for fn in files:
  358. # comment out next suite to leave .pyc files in
  359. if fsdecode(fn).endswith(('.pyc', '.pyo')):
  360. continue
  361. p = os.path.join(root, fn)
  362. rp = to_posix(os.path.relpath(p, path))
  363. archive_paths.append((rp, p))
  364. # Now distinfo. Assumed to be flat, i.e. os.listdir is enough.
  365. files = os.listdir(distinfo)
  366. for fn in files:
  367. if fn not in ('RECORD', 'INSTALLER', 'SHARED', 'WHEEL'):
  368. p = fsdecode(os.path.join(distinfo, fn))
  369. ap = to_posix(os.path.join(info_dir, fn))
  370. archive_paths.append((ap, p))
  371. wheel_metadata = [
  372. 'Wheel-Version: %d.%d' % (wheel_version or self.wheel_version),
  373. 'Generator: distlib %s' % __version__,
  374. 'Root-Is-Purelib: %s' % is_pure,
  375. ]
  376. for pyver, abi, arch in self.tags:
  377. wheel_metadata.append('Tag: %s-%s-%s' % (pyver, abi, arch))
  378. p = os.path.join(distinfo, 'WHEEL')
  379. with open(p, 'w') as f:
  380. f.write('\n'.join(wheel_metadata))
  381. ap = to_posix(os.path.join(info_dir, 'WHEEL'))
  382. archive_paths.append((ap, p))
  383. # sort the entries by archive path. Not needed by any spec, but it
  384. # keeps the archive listing and RECORD tidier than they would otherwise
  385. # be. Use the number of path segments to keep directory entries together,
  386. # and keep the dist-info stuff at the end.
  387. def sorter(t):
  388. ap = t[0]
  389. n = ap.count('/')
  390. if '.dist-info' in ap:
  391. n += 10000
  392. return (n, ap)
  393. archive_paths = sorted(archive_paths, key=sorter)
  394. # Now, at last, RECORD.
  395. # Paths in here are archive paths - nothing else makes sense.
  396. self.write_records((distinfo, info_dir), libdir, archive_paths)
  397. # Now, ready to build the zip file
  398. pathname = os.path.join(self.dirname, self.filename)
  399. self.build_zip(pathname, archive_paths)
  400. return pathname
  401. def skip_entry(self, arcname):
  402. """
  403. Determine whether an archive entry should be skipped when verifying
  404. or installing.
  405. """
  406. # The signature file won't be in RECORD,
  407. # and we don't currently don't do anything with it
  408. # We also skip directories, as they won't be in RECORD
  409. # either. See:
  410. #
  411. # https://github.com/pypa/wheel/issues/294
  412. # https://github.com/pypa/wheel/issues/287
  413. # https://github.com/pypa/wheel/pull/289
  414. #
  415. return arcname.endswith(('/', '/RECORD.jws'))
  416. def install(self, paths, maker, **kwargs):
  417. """
  418. Install a wheel to the specified paths. If kwarg ``warner`` is
  419. specified, it should be a callable, which will be called with two
  420. tuples indicating the wheel version of this software and the wheel
  421. version in the file, if there is a discrepancy in the versions.
  422. This can be used to issue any warnings to raise any exceptions.
  423. If kwarg ``lib_only`` is True, only the purelib/platlib files are
  424. installed, and the headers, scripts, data and dist-info metadata are
  425. not written. If kwarg ``bytecode_hashed_invalidation`` is True, written
  426. bytecode will try to use file-hash based invalidation (PEP-552) on
  427. supported interpreter versions (CPython 2.7+).
  428. The return value is a :class:`InstalledDistribution` instance unless
  429. ``options.lib_only`` is True, in which case the return value is ``None``.
  430. """
  431. dry_run = maker.dry_run
  432. warner = kwargs.get('warner')
  433. lib_only = kwargs.get('lib_only', False)
  434. bc_hashed_invalidation = kwargs.get('bytecode_hashed_invalidation', False)
  435. pathname = os.path.join(self.dirname, self.filename)
  436. name_ver = '%s-%s' % (self.name, self.version)
  437. data_dir = '%s.data' % name_ver
  438. info_dir = '%s.dist-info' % name_ver
  439. metadata_name = posixpath.join(info_dir, LEGACY_METADATA_FILENAME)
  440. wheel_metadata_name = posixpath.join(info_dir, 'WHEEL')
  441. record_name = posixpath.join(info_dir, 'RECORD')
  442. wrapper = codecs.getreader('utf-8')
  443. with ZipFile(pathname, 'r') as zf:
  444. with zf.open(wheel_metadata_name) as bwf:
  445. wf = wrapper(bwf)
  446. message = message_from_file(wf)
  447. wv = message['Wheel-Version'].split('.', 1)
  448. file_version = tuple([int(i) for i in wv])
  449. if (file_version != self.wheel_version) and warner:
  450. warner(self.wheel_version, file_version)
  451. if message['Root-Is-Purelib'] == 'true':
  452. libdir = paths['purelib']
  453. else:
  454. libdir = paths['platlib']
  455. records = {}
  456. with zf.open(record_name) as bf:
  457. with CSVReader(stream=bf) as reader:
  458. for row in reader:
  459. p = row[0]
  460. records[p] = row
  461. data_pfx = posixpath.join(data_dir, '')
  462. info_pfx = posixpath.join(info_dir, '')
  463. script_pfx = posixpath.join(data_dir, 'scripts', '')
  464. # make a new instance rather than a copy of maker's,
  465. # as we mutate it
  466. fileop = FileOperator(dry_run=dry_run)
  467. fileop.record = True # so we can rollback if needed
  468. bc = not sys.dont_write_bytecode # Double negatives. Lovely!
  469. outfiles = [] # for RECORD writing
  470. # for script copying/shebang processing
  471. workdir = tempfile.mkdtemp()
  472. # set target dir later
  473. # we default add_launchers to False, as the
  474. # Python Launcher should be used instead
  475. maker.source_dir = workdir
  476. maker.target_dir = None
  477. try:
  478. for zinfo in zf.infolist():
  479. arcname = zinfo.filename
  480. if isinstance(arcname, text_type):
  481. u_arcname = arcname
  482. else:
  483. u_arcname = arcname.decode('utf-8')
  484. if self.skip_entry(u_arcname):
  485. continue
  486. row = records[u_arcname]
  487. if row[2] and str(zinfo.file_size) != row[2]:
  488. raise DistlibException('size mismatch for '
  489. '%s' % u_arcname)
  490. if row[1]:
  491. kind, value = row[1].split('=', 1)
  492. with zf.open(arcname) as bf:
  493. data = bf.read()
  494. _, digest = self.get_hash(data, kind)
  495. if digest != value:
  496. raise DistlibException('digest mismatch for '
  497. '%s' % arcname)
  498. if lib_only and u_arcname.startswith((info_pfx, data_pfx)):
  499. logger.debug('lib_only: skipping %s', u_arcname)
  500. continue
  501. is_script = (u_arcname.startswith(script_pfx)
  502. and not u_arcname.endswith('.exe'))
  503. if u_arcname.startswith(data_pfx):
  504. _, where, rp = u_arcname.split('/', 2)
  505. outfile = os.path.join(paths[where], convert_path(rp))
  506. else:
  507. # meant for site-packages.
  508. if u_arcname in (wheel_metadata_name, record_name):
  509. continue
  510. outfile = os.path.join(libdir, convert_path(u_arcname))
  511. if not is_script:
  512. with zf.open(arcname) as bf:
  513. fileop.copy_stream(bf, outfile)
  514. outfiles.append(outfile)
  515. # Double check the digest of the written file
  516. if not dry_run and row[1]:
  517. with open(outfile, 'rb') as bf:
  518. data = bf.read()
  519. _, newdigest = self.get_hash(data, kind)
  520. if newdigest != digest:
  521. raise DistlibException('digest mismatch '
  522. 'on write for '
  523. '%s' % outfile)
  524. if bc and outfile.endswith('.py'):
  525. try:
  526. pyc = fileop.byte_compile(outfile,
  527. hashed_invalidation=bc_hashed_invalidation)
  528. outfiles.append(pyc)
  529. except Exception:
  530. # Don't give up if byte-compilation fails,
  531. # but log it and perhaps warn the user
  532. logger.warning('Byte-compilation failed',
  533. exc_info=True)
  534. else:
  535. fn = os.path.basename(convert_path(arcname))
  536. workname = os.path.join(workdir, fn)
  537. with zf.open(arcname) as bf:
  538. fileop.copy_stream(bf, workname)
  539. dn, fn = os.path.split(outfile)
  540. maker.target_dir = dn
  541. filenames = maker.make(fn)
  542. fileop.set_executable_mode(filenames)
  543. outfiles.extend(filenames)
  544. if lib_only:
  545. logger.debug('lib_only: returning None')
  546. dist = None
  547. else:
  548. # Generate scripts
  549. # Try to get pydist.json so we can see if there are
  550. # any commands to generate. If this fails (e.g. because
  551. # of a legacy wheel), log a warning but don't give up.
  552. commands = None
  553. file_version = self.info['Wheel-Version']
  554. if file_version == '1.0':
  555. # Use legacy info
  556. ep = posixpath.join(info_dir, 'entry_points.txt')
  557. try:
  558. with zf.open(ep) as bwf:
  559. epdata = read_exports(bwf)
  560. commands = {}
  561. for key in ('console', 'gui'):
  562. k = '%s_scripts' % key
  563. if k in epdata:
  564. commands['wrap_%s' % key] = d = {}
  565. for v in epdata[k].values():
  566. s = '%s:%s' % (v.prefix, v.suffix)
  567. if v.flags:
  568. s += ' [%s]' % ','.join(v.flags)
  569. d[v.name] = s
  570. except Exception:
  571. logger.warning('Unable to read legacy script '
  572. 'metadata, so cannot generate '
  573. 'scripts')
  574. else:
  575. try:
  576. with zf.open(metadata_name) as bwf:
  577. wf = wrapper(bwf)
  578. commands = json.load(wf).get('extensions')
  579. if commands:
  580. commands = commands.get('python.commands')
  581. except Exception:
  582. logger.warning('Unable to read JSON metadata, so '
  583. 'cannot generate scripts')
  584. if commands:
  585. console_scripts = commands.get('wrap_console', {})
  586. gui_scripts = commands.get('wrap_gui', {})
  587. if console_scripts or gui_scripts:
  588. script_dir = paths.get('scripts', '')
  589. if not os.path.isdir(script_dir):
  590. raise ValueError('Valid script path not '
  591. 'specified')
  592. maker.target_dir = script_dir
  593. for k, v in console_scripts.items():
  594. script = '%s = %s' % (k, v)
  595. filenames = maker.make(script)
  596. fileop.set_executable_mode(filenames)
  597. if gui_scripts:
  598. options = {'gui': True }
  599. for k, v in gui_scripts.items():
  600. script = '%s = %s' % (k, v)
  601. filenames = maker.make(script, options)
  602. fileop.set_executable_mode(filenames)
  603. p = os.path.join(libdir, info_dir)
  604. dist = InstalledDistribution(p)
  605. # Write SHARED
  606. paths = dict(paths) # don't change passed in dict
  607. del paths['purelib']
  608. del paths['platlib']
  609. paths['lib'] = libdir
  610. p = dist.write_shared_locations(paths, dry_run)
  611. if p:
  612. outfiles.append(p)
  613. # Write RECORD
  614. dist.write_installed_files(outfiles, paths['prefix'],
  615. dry_run)
  616. return dist
  617. except Exception: # pragma: no cover
  618. logger.exception('installation failed.')
  619. fileop.rollback()
  620. raise
  621. finally:
  622. shutil.rmtree(workdir)
  623. def _get_dylib_cache(self):
  624. global cache
  625. if cache is None:
  626. # Use native string to avoid issues on 2.x: see Python #20140.
  627. base = os.path.join(get_cache_base(), str('dylib-cache'),
  628. '%s.%s' % sys.version_info[:2])
  629. cache = Cache(base)
  630. return cache
  631. def _get_extensions(self):
  632. pathname = os.path.join(self.dirname, self.filename)
  633. name_ver = '%s-%s' % (self.name, self.version)
  634. info_dir = '%s.dist-info' % name_ver
  635. arcname = posixpath.join(info_dir, 'EXTENSIONS')
  636. wrapper = codecs.getreader('utf-8')
  637. result = []
  638. with ZipFile(pathname, 'r') as zf:
  639. try:
  640. with zf.open(arcname) as bf:
  641. wf = wrapper(bf)
  642. extensions = json.load(wf)
  643. cache = self._get_dylib_cache()
  644. prefix = cache.prefix_to_dir(pathname)
  645. cache_base = os.path.join(cache.base, prefix)
  646. if not os.path.isdir(cache_base):
  647. os.makedirs(cache_base)
  648. for name, relpath in extensions.items():
  649. dest = os.path.join(cache_base, convert_path(relpath))
  650. if not os.path.exists(dest):
  651. extract = True
  652. else:
  653. file_time = os.stat(dest).st_mtime
  654. file_time = datetime.datetime.fromtimestamp(file_time)
  655. info = zf.getinfo(relpath)
  656. wheel_time = datetime.datetime(*info.date_time)
  657. extract = wheel_time > file_time
  658. if extract:
  659. zf.extract(relpath, cache_base)
  660. result.append((name, dest))
  661. except KeyError:
  662. pass
  663. return result
  664. def is_compatible(self):
  665. """
  666. Determine if a wheel is compatible with the running system.
  667. """
  668. return is_compatible(self)
  669. def is_mountable(self):
  670. """
  671. Determine if a wheel is asserted as mountable by its metadata.
  672. """
  673. return True # for now - metadata details TBD
  674. def mount(self, append=False):
  675. pathname = os.path.abspath(os.path.join(self.dirname, self.filename))
  676. if not self.is_compatible():
  677. msg = 'Wheel %s not compatible with this Python.' % pathname
  678. raise DistlibException(msg)
  679. if not self.is_mountable():
  680. msg = 'Wheel %s is marked as not mountable.' % pathname
  681. raise DistlibException(msg)
  682. if pathname in sys.path:
  683. logger.debug('%s already in path', pathname)
  684. else:
  685. if append:
  686. sys.path.append(pathname)
  687. else:
  688. sys.path.insert(0, pathname)
  689. extensions = self._get_extensions()
  690. if extensions:
  691. if _hook not in sys.meta_path:
  692. sys.meta_path.append(_hook)
  693. _hook.add(pathname, extensions)
  694. def unmount(self):
  695. pathname = os.path.abspath(os.path.join(self.dirname, self.filename))
  696. if pathname not in sys.path:
  697. logger.debug('%s not in path', pathname)
  698. else:
  699. sys.path.remove(pathname)
  700. if pathname in _hook.impure_wheels:
  701. _hook.remove(pathname)
  702. if not _hook.impure_wheels:
  703. if _hook in sys.meta_path:
  704. sys.meta_path.remove(_hook)
  705. def verify(self):
  706. pathname = os.path.join(self.dirname, self.filename)
  707. name_ver = '%s-%s' % (self.name, self.version)
  708. data_dir = '%s.data' % name_ver
  709. info_dir = '%s.dist-info' % name_ver
  710. metadata_name = posixpath.join(info_dir, LEGACY_METADATA_FILENAME)
  711. wheel_metadata_name = posixpath.join(info_dir, 'WHEEL')
  712. record_name = posixpath.join(info_dir, 'RECORD')
  713. wrapper = codecs.getreader('utf-8')
  714. with ZipFile(pathname, 'r') as zf:
  715. with zf.open(wheel_metadata_name) as bwf:
  716. wf = wrapper(bwf)
  717. message = message_from_file(wf)
  718. wv = message['Wheel-Version'].split('.', 1)
  719. file_version = tuple([int(i) for i in wv])
  720. # TODO version verification
  721. records = {}
  722. with zf.open(record_name) as bf:
  723. with CSVReader(stream=bf) as reader:
  724. for row in reader:
  725. p = row[0]
  726. records[p] = row
  727. for zinfo in zf.infolist():
  728. arcname = zinfo.filename
  729. if isinstance(arcname, text_type):
  730. u_arcname = arcname
  731. else:
  732. u_arcname = arcname.decode('utf-8')
  733. # See issue #115: some wheels have .. in their entries, but
  734. # in the filename ... e.g. __main__..py ! So the check is
  735. # updated to look for .. in the directory portions
  736. p = u_arcname.split('/')
  737. if '..' in p:
  738. raise DistlibException('invalid entry in '
  739. 'wheel: %r' % u_arcname)
  740. if self.skip_entry(u_arcname):
  741. continue
  742. row = records[u_arcname]
  743. if row[2] and str(zinfo.file_size) != row[2]:
  744. raise DistlibException('size mismatch for '
  745. '%s' % u_arcname)
  746. if row[1]:
  747. kind, value = row[1].split('=', 1)
  748. with zf.open(arcname) as bf:
  749. data = bf.read()
  750. _, digest = self.get_hash(data, kind)
  751. if digest != value:
  752. raise DistlibException('digest mismatch for '
  753. '%s' % arcname)
  754. def update(self, modifier, dest_dir=None, **kwargs):
  755. """
  756. Update the contents of a wheel in a generic way. The modifier should
  757. be a callable which expects a dictionary argument: its keys are
  758. archive-entry paths, and its values are absolute filesystem paths
  759. where the contents the corresponding archive entries can be found. The
  760. modifier is free to change the contents of the files pointed to, add
  761. new entries and remove entries, before returning. This method will
  762. extract the entire contents of the wheel to a temporary location, call
  763. the modifier, and then use the passed (and possibly updated)
  764. dictionary to write a new wheel. If ``dest_dir`` is specified, the new
  765. wheel is written there -- otherwise, the original wheel is overwritten.
  766. The modifier should return True if it updated the wheel, else False.
  767. This method returns the same value the modifier returns.
  768. """
  769. def get_version(path_map, info_dir):
  770. version = path = None
  771. key = '%s/%s' % (info_dir, LEGACY_METADATA_FILENAME)
  772. if key not in path_map:
  773. key = '%s/PKG-INFO' % info_dir
  774. if key in path_map:
  775. path = path_map[key]
  776. version = Metadata(path=path).version
  777. return version, path
  778. def update_version(version, path):
  779. updated = None
  780. try:
  781. v = NormalizedVersion(version)
  782. i = version.find('-')
  783. if i < 0:
  784. updated = '%s+1' % version
  785. else:
  786. parts = [int(s) for s in version[i + 1:].split('.')]
  787. parts[-1] += 1
  788. updated = '%s+%s' % (version[:i],
  789. '.'.join(str(i) for i in parts))
  790. except UnsupportedVersionError:
  791. logger.debug('Cannot update non-compliant (PEP-440) '
  792. 'version %r', version)
  793. if updated:
  794. md = Metadata(path=path)
  795. md.version = updated
  796. legacy = path.endswith(LEGACY_METADATA_FILENAME)
  797. md.write(path=path, legacy=legacy)
  798. logger.debug('Version updated from %r to %r', version,
  799. updated)
  800. pathname = os.path.join(self.dirname, self.filename)
  801. name_ver = '%s-%s' % (self.name, self.version)
  802. info_dir = '%s.dist-info' % name_ver
  803. record_name = posixpath.join(info_dir, 'RECORD')
  804. with tempdir() as workdir:
  805. with ZipFile(pathname, 'r') as zf:
  806. path_map = {}
  807. for zinfo in zf.infolist():
  808. arcname = zinfo.filename
  809. if isinstance(arcname, text_type):
  810. u_arcname = arcname
  811. else:
  812. u_arcname = arcname.decode('utf-8')
  813. if u_arcname == record_name:
  814. continue
  815. if '..' in u_arcname:
  816. raise DistlibException('invalid entry in '
  817. 'wheel: %r' % u_arcname)
  818. zf.extract(zinfo, workdir)
  819. path = os.path.join(workdir, convert_path(u_arcname))
  820. path_map[u_arcname] = path
  821. # Remember the version.
  822. original_version, _ = get_version(path_map, info_dir)
  823. # Files extracted. Call the modifier.
  824. modified = modifier(path_map, **kwargs)
  825. if modified:
  826. # Something changed - need to build a new wheel.
  827. current_version, path = get_version(path_map, info_dir)
  828. if current_version and (current_version == original_version):
  829. # Add or update local version to signify changes.
  830. update_version(current_version, path)
  831. # Decide where the new wheel goes.
  832. if dest_dir is None:
  833. fd, newpath = tempfile.mkstemp(suffix='.whl',
  834. prefix='wheel-update-',
  835. dir=workdir)
  836. os.close(fd)
  837. else:
  838. if not os.path.isdir(dest_dir):
  839. raise DistlibException('Not a directory: %r' % dest_dir)
  840. newpath = os.path.join(dest_dir, self.filename)
  841. archive_paths = list(path_map.items())
  842. distinfo = os.path.join(workdir, info_dir)
  843. info = distinfo, info_dir
  844. self.write_records(info, workdir, archive_paths)
  845. self.build_zip(newpath, archive_paths)
  846. if dest_dir is None:
  847. shutil.copyfile(newpath, pathname)
  848. return modified
  849. def compatible_tags():
  850. """
  851. Return (pyver, abi, arch) tuples compatible with this Python.
  852. """
  853. versions = [VER_SUFFIX]
  854. major = VER_SUFFIX[0]
  855. for minor in range(sys.version_info[1] - 1, - 1, -1):
  856. versions.append(''.join([major, str(minor)]))
  857. abis = []
  858. for suffix, _, _ in imp.get_suffixes():
  859. if suffix.startswith('.abi'):
  860. abis.append(suffix.split('.', 2)[1])
  861. abis.sort()
  862. if ABI != 'none':
  863. abis.insert(0, ABI)
  864. abis.append('none')
  865. result = []
  866. arches = [ARCH]
  867. if sys.platform == 'darwin':
  868. m = re.match(r'(\w+)_(\d+)_(\d+)_(\w+)$', ARCH)
  869. if m:
  870. name, major, minor, arch = m.groups()
  871. minor = int(minor)
  872. matches = [arch]
  873. if arch in ('i386', 'ppc'):
  874. matches.append('fat')
  875. if arch in ('i386', 'ppc', 'x86_64'):
  876. matches.append('fat3')
  877. if arch in ('ppc64', 'x86_64'):
  878. matches.append('fat64')
  879. if arch in ('i386', 'x86_64'):
  880. matches.append('intel')
  881. if arch in ('i386', 'x86_64', 'intel', 'ppc', 'ppc64'):
  882. matches.append('universal')
  883. while minor >= 0:
  884. for match in matches:
  885. s = '%s_%s_%s_%s' % (name, major, minor, match)
  886. if s != ARCH: # already there
  887. arches.append(s)
  888. minor -= 1
  889. # Most specific - our Python version, ABI and arch
  890. for abi in abis:
  891. for arch in arches:
  892. result.append((''.join((IMP_PREFIX, versions[0])), abi, arch))
  893. # where no ABI / arch dependency, but IMP_PREFIX dependency
  894. for i, version in enumerate(versions):
  895. result.append((''.join((IMP_PREFIX, version)), 'none', 'any'))
  896. if i == 0:
  897. result.append((''.join((IMP_PREFIX, version[0])), 'none', 'any'))
  898. # no IMP_PREFIX, ABI or arch dependency
  899. for i, version in enumerate(versions):
  900. result.append((''.join(('py', version)), 'none', 'any'))
  901. if i == 0:
  902. result.append((''.join(('py', version[0])), 'none', 'any'))
  903. return set(result)
  904. COMPATIBLE_TAGS = compatible_tags()
  905. del compatible_tags
  906. def is_compatible(wheel, tags=None):
  907. if not isinstance(wheel, Wheel):
  908. wheel = Wheel(wheel) # assume it's a filename
  909. result = False
  910. if tags is None:
  911. tags = COMPATIBLE_TAGS
  912. for ver, abi, arch in tags:
  913. if ver in wheel.pyver and abi in wheel.abi and arch in wheel.arch:
  914. result = True
  915. break
  916. return result